import { CommonModel } from "../../models/login.js"
import { oneOf, urlEncode } from '../../utils/util.js'
import { reg_passWord, reg_Tel } from '../../utils/reg.js'
let loginModel = new CommonModel()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userPhone: '',
    btnTxt: "获取验证码",
    btnUse: true,
    historyPath: '',//登录进来的历史页面
    params: '',//历史页面的参数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  getHistoryPath() {
    let pages = getCurrentPages();
    console.log(pages);
    if (pages.length > 1) {
      let params = pages[pages.length - 2].options;
      params = urlEncode(params, '', false);
      this.setData({
        historyPath: pages[pages.length - 2].route,
        params,
      })
      console.log(this.data.historyPath, params)
    }
  },

  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    console.log(e);
    let formData = e.detail.value;
    let username = formData.username || '';
    let password = formData.password;
    if (!username) {
      wx.showToast({
        title: "请输入手机号/工号",
        icon: 'none',
        duration: 2000
      })
      return
    } else if (!password) {
      wx.showToast({
        title: "请输入密码",
        icon: 'none',
        duration: 2000
      })
      return
    } else if (!reg_passWord.test(password)) {
      wx.showToast({
        title: "请输入6到12位密码",
        icon: 'none',
        duration: 2000
      })
      return
    }
    loginModel.login(username,password).then(res => {
      if (res.result) {
        wx.setStorage({
          key: 'loginInfo',
          data: res.data,
        })
        this.goHistoryPath()
      } else {
        wx.showToast({
          title: !!res.message.global ? res.message.global : "请求出错",
          icon: "none"
        })
      }
    }).catch(res => {
      console.log(res, 'login4')

    })

  },
  goHistoryPath() {
    if (this.data.historyPath) {
      let tabPath = ["pages/index/index", "pages/book/book", "pages/my/my",]
      // if (oneOf(this.data.historyPath, tabPath)) {
      //   wx.switchTab({
      //     url: '/' + this.data.historyPath,
      //   })
      // } else {
      //   let path = '/' + this.data.historyPath;
      //   console.log(path)
      //   wx.redirectTo({
      //     url: `${path}?${this.data.params}`
      //   })
      // }
      let path = '/' + this.data.historyPath;
      wx.reLaunch({
        url: `${path}?${this.data.params}`
      })
    } else {
      wx.switchTab({
        url: '../index/index',
      })
    }
  },
  formReset: function () {
    console.log('form发生了reset事件')
  },
})